from Images import cacheImage
from Block import Block
from Errors import *

from pygame.locals import *
from Constants import *

class Cursor:
    def __init__(self, map, puzzleHandler, sideBar, pos=(2,2)):
        cursorCache = {}
        cacheImage(cursorCache,'Selector')
        self.puzzleHandler = puzzleHandler
        self.cursor = Block('Selector', cursorCache)
        #TODO: badness, circular reference
        self.world = map
        self.world.cursor = self
        self.moveCursorTo(pos[X],pos[Y])
        self.grabbed = None
        self.sideBar = sideBar
    
    def render(self, screen):
        y = TILE_Y_SPACING * self.y - TILE_DEPTH * (self.z-2) 
        x = TILE_WIDTH * self.x
        self.cursor.render(screen, x , y)
        
    def moveCursorTo(self, x, y):
        self.x = x
        self.y = y
        self.z = self.world.stacks[x][y].size()
        if x > 0:
            self.world.updateRow(x-1,y)
        self.world.updateRow(x,y)
        if x < len(self.world.stacks)-1:
            self.world.updateRow(x+1,y)
    
    def cursorUp(self):
        if self.y > 0:
            self.moveCursorTo(self.x, self.y - 1)
    
    def cursorDown(self):
        if self.y < MAP_Y-1:
            self.moveCursorTo(self.x, self.y + 1)
    
    def cursorLeft(self):
        if self.x > 0:
            self.moveCursorTo(self.x - 1, self.y)
    
    def cursorRight(self):
        if self.x < MAP_X-1:
            self.moveCursorTo(self.x + 1, self.y)
    
    def mapKeys(self, keyHandler):
        keyHandler[K_UP] = self.cursorUp
        keyHandler[K_DOWN] = self.cursorDown
        keyHandler[K_LEFT] = self.cursorLeft
        keyHandler[K_RIGHT] = self.cursorRight
        keyHandler[K_SPACE] = self.yoink
        
    def yoink(self):
        if self.grabbed == None:
            self.grabbed = self.world.grab(self.x, self.y)
        else:
            self.grabbed = self.world.drop(self.grabbed, self.x, self.y)
            if self.grabbed == None:
                solved = self.puzzleHandler.handleDrop(self.world, self.x, self.y)
                if solved != None:
                    self.sideBar.removePuzzle(solved)
    
    def mouseMoved(self, pos):
        mouseX = pos[0]
        mouseY = pos[1]
        x = int(mouseX / TILE_WIDTH)
        y = int(mouseY / TILE_HEIGHT)
        if x != self.x or y != self.y:
            self.moveCursorTo(x, y)
            return True
        else:
            return False
    